package clientapp;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import serverapp.Player;

/**
 *
 * @author a
 */
public class ConnectionHandler implements Runnable {

    private Socket client;
    private OutputStream out;
    private InputStream in;
    private ObjectInputStream inObject;
    private ObjectOutputStream outObject;
    public ArrayList players;
    public ArrayList panels = new ArrayList();

    public ConnectionHandler(Socket aClient) {
        this.client = aClient;
    }

    @Override
    public void run() {
        try {
            out = client.getOutputStream();
            in = client.getInputStream();
            while (true) {
                while (in.available() > 0) {
                    players = getPlayers();
                    for (int i = 0; i < players.size(); i++) {
                        Player player = (Player) players.get(i);
                        playerPanel newPanel = new playerPanel(player);
                        panels.add(newPanel);
                    }
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ArrayList getPlayers() {
        ArrayList playerList = new ArrayList();
        try {
            System.out.println("Receiving players ...");
            inObject = new ObjectInputStream(client.getInputStream());
            playerList = (ArrayList) inObject.readObject();
            System.out.println("Players received.");
        } catch (IOException ex) {
            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return playerList;
    }

    public void sendPlayers(ArrayList aPlayerList) {
        try {
            System.out.println("Sending players");
            outObject = new ObjectOutputStream(client.getOutputStream());
            outObject.writeObject(aPlayerList);
            System.out.println("Players sent");
        } catch (IOException ex) {
            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}